<template>
  <div style="margin-top: 20px">
    <el-row :gutter="15">
      <el-form ref="searchForm" :model="searchData" size="medium" label-width="100px">
        <el-col :span="16">
          <el-form-item label="门诊号" prop="clinicNo">
            <el-input v-model="searchData.clinicNo" placeholder="请输入门诊号" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="类别" prop="typeOrder">
            <el-select v-model="searchData.typeOrder" placeholder="请选择类别" :style="{width: '100%'}">
              <el-option v-for="(item, index) in kindOptions" :key="index" :label="item.label"
                         :value="item.value" :disabled="item.disabled"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="患者" prop="patientId">
            <!--<el-input v-model="searchData.patientId" placeholder="请输入患者" clearable :style="{width: '100%'}">
            </el-input>-->
            <el-autocomplete
              v-model="searchData.name"
              :fetch-suggestions="getNameData"
              placeholder="请输入姓名"
              @select="getChoose"
              clearable
            ></el-autocomplete>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="支付情况" prop="payResult">
            <el-select v-model="searchData.payResult" placeholder="请选择下拉选择" :style="{width: '100%'}">
              <el-option v-for="(item, index) in payResultOptions" :key="index" :label="item.label"
                         :value="item.value" :disabled="item.disabled"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="日期范围" prop="field111">
            <el-date-picker type="datetimerange" v-model="searchData.rangeDate" format="yyyy-MM-dd HH:mm:ss"
                            value-format="yyyy-MM-dd HH:mm:ss" :style="{width: '100%'}" start-placeholder="开始日期"
                            end-placeholder="结束日期" range-separator="至" clearable></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item size="large">
            <el-button type="primary" @click="submitForm">提交</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>

    <el-table
      :data="dataList"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      :row-class-name="tableRowClassName"
      v-show="dataList.length > 0"
    >
      <el-table-column label="门诊号" prop="clinicNo" align="center" width="180">
        <template slot-scope="{ row }">
          <span>{{ row.clinicNo }}</span>
        </template>
      </el-table-column>

      <el-table-column label="商户订单" prop="orderCode" align="center" width="200">
        <template slot-scope="{ row }">
          <span>{{ row.orderCode }}</span>
        </template>
      </el-table-column>

      <el-table-column label="姓名" prop="patientName" align="center">
        <template slot-scope="{ row }">
          <el-popover trigger="hover" placement="top">
            <p>姓名: {{ row.patientName }}</p>
            <p>联系电话: {{ row.tel | hideTel }}</p>
            <p>住址: {{ row.addr }}</p>
            <div slot="reference" class="name-wrapper">
              <el-tag size="medium">{{ row.patientName }}</el-tag>
            </div>
          </el-popover>
        </template>
      </el-table-column>

      <el-table-column label="主治医生" prop="doctorName" align="center">
        <template slot-scope="{ row }">
          <span>
            {{row.doctorName}}
          </span>
        </template>
      </el-table-column>

      <el-table-column label="订单类型" prop="typeOrder" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.typeOrder | orderKind }}</span>
        </template>
      </el-table-column>

      <!--<el-table-column label="手机号码" prop="tel" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.tel | hideTel }}</span>
        </template>
      </el-table-column>-->

      <el-table-column label="金额" prop="amount" align="center">
        <template slot-scope="{ row }">
          <span>￥{{ new Number(row.amount).toFixed(2) }}元</span>
        </template>
      </el-table-column>

      <el-table-column label="下单时间" prop="orderDate" align="center" width="160">
        <template slot-scope="{ row }">
          <span>{{ row.orderDate | timeFormat }}</span>
        </template>
      </el-table-column>

      <el-table-column label="支付情况" prop="payResult" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.payResult | showFinish  }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" prop="id" align="center" width="200">
        <template slot-scope="{ row }">
          <el-popover trigger="hover" placement="top" v-if="row.payResult == 0 || row.payResult == 2">
            <el-button type="primary" @click="check(row,1)">
              <span>现金支付</span>
            </el-button>
            <el-button type="info" :disabled="true" @click="check(row,2)">
              <span>扫码支付</span>
            </el-button>
            <el-button type="info" :disabled="true" @click="check(row,0)">
              <span>刷卡支付</span>
            </el-button>
            <el-button type="danger" @click="check(row,3)">
              <span>取消支付</span>
            </el-button>
            <div slot="reference" class="name-wrapper">
              <el-tag size="medium">支付</el-tag>
            </div>
          </el-popover>
        </template>
      </el-table-column>
    </el-table>

    <!--<el-pagination v-show="dataList.length > 0"
                   :page-size="searchData.pageSize"
                   layout="prev, pager, next"
                   :total="searchData.totalCount"
                   @prev-click="submitForm(-1)"
                   @next-click="submitForm(1)"
    ></el-pagination>-->


    <pagination
      :total="searchData.totalCount"
      :page.sync="searchData.page"
      :limit.sync="searchData.pageSize"
      @pagination="submitForm"
    />

  </div>
</template>
<script>
  import {getPatients} from "@/api/patient";
  import {getTreatRecord} from "@/api/treatRecord";
  import {searchOrder, orderCash, orderCancel} from "@/api/order";
  import {getDay, formatDate} from "@/utils/date";
  import Pagination from "@/components/Pagination";

  export default {
    components: {Pagination},
    name: "orderRecord",
    data() {
      return {
        dataList: [],
        searchData: {
          clinicNo: null,
          kind: null,
          patientId: null,
          isFinish: null,
          rangeDate: ["", ""],
          page: 0,
          totalCount: 0,
          totalPage: 1,
          pageSize: 10
        },
        kindOptions: [
          {"value": "0", "label": "门诊就诊"},
          {"value": "1", "label": "视光销售"},
          {"value": "2", "label": "加工申请"}
        ],
        payResultOptions: [
          {"value": "0", "label": "预支付申请"},
          {"value": "1", "label": "完成支付"},
          {"value": "2", "label": "第三方订单待支付"},
          {"value": "3", "label": "取消"},
          {"value": "9", "label": "超时失效"}
        ],
      }
    },
    computed: {
      newName() {
        return this.searchData.name;
      }
    },
    watch: {
      newName(val) {
        this.value = val;
        if (this.searchData.name === "") {
          this.searchData.patientId = null
        }
      }
    },
    created() {
      window.app = this
      this.searchData.rangeDate[1] = formatDate(getDay(0))
      this.searchData.rangeDate[0] = formatDate(getDay(-7))
      this.submitForm();
    },
    filters: {
      timeFormat(t) {
        return new Date(t).Format("yyyy-MM-dd hh:mm:ss");
      },
      hideTel(tel) {
        if (!tel) return
        var reg = /^(\d{3})\d{4}(\d{4})$/;
        return tel.replace(reg, "$1****$2");
      },
      showFinish(k) {
        let result = {0: "预支付申请", 1: "完成支付", 2: "第三方订单待支付", 3: "取消", 9: "超时失效"}
        return result[k]
      },
      orderKind(k) {
        let o = {0: "门诊就诊", 1: "视光销售", 2: "加工申请"}
        return o[k]
      },
      showGender(d) {
        let gender = {1: "男", 2: "女"};
        return gender[d];
      },
      age(strBirthday) {
        if (strBirthday) {
          let strBirthdayArr = strBirthday.split("-");
          let d = new Date();
          let yearDiff = d.getFullYear() - strBirthdayArr[0];
          let monthDiff = d.getMonth() + 1 - strBirthdayArr[1];
          let dayDiff = d.getDate() - strBirthdayArr[2];
          let age = monthDiff < 0 || (monthDiff === 0 && dayDiff < 0) ? yearDiff - 1 : yearDiff;
          //判断有没有到生日,没到就减1
          return age <= 0 ? monthDiff + "月" : age + "岁";
        }
      }
    },
    mounted() {
    },
    methods: {
      tableRowClassName({row, rowIndex}) {
        if (row.isFinish === "1") {
          return 'success-row';
        }
        return '';
      },
      check(row, status) {

        let d = {
          payResult: 1,
          batchNo: row.batchNo,
          id: row.id,
          version: row.version
        }

        switch (status) {
          case 1:
            console.log("现金支付");
            this.$confirm('将使用现金支付, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              console.log("------------")
              console.log(d)
              console.log("------------")
              orderCash(d).then(response => {
                if (response.code === 200) {
                  this.$message({
                    type: 'success',
                    message: '现金支付成功!'
                  });
                  row.payResult = d.payResult
                  row.version++
                }
              })
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消操作'
              });
            });
            break;
          case 2:
            console.log("扫码支付")
            break;
          case 0:
            console.log("刷卡支付")
            break;
          case 3:
            console.log("取消支付");
            this.$confirm('此操作将直接取消订单,并释放商品库存, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              d.payResult = 3
              orderCancel(d).then(response => {
                if (response.code === 200) {
                  this.$message({
                    type: 'success',
                    message: '取消订单成功!'
                  });
                  row.version++
                }
              })
              row.payResult = 3
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消操作'
              });
            });
            break;
        }
      },
      geTel(tel) {
        var reg = /^(\d{3})\d{4}(\d{4})$/;
        return tel.replace(reg, "$1****$2");
      },
      remote(data, cb) {
        let _that = this;
        getPatients(data).then(response => {
          if (response.code === 200) {
            let data = response.page.list;
            data.filter(function (a) {
              a.value = a.name + "-" + _that.geTel(a.tel);
            });
            cb(data);
          }
        });
      },
      //查询病人信息select
      getNameData(queryString, cb) {
        this.remote({name: queryString}, cb);
      },
      //获取病人名字查询
      getChoose(val) {
        this.searchData.patientId = val.id;
        this.searchData.page = 0;
        this.searchData.pageSize = 10;
        this.submitForm()
      },
      submitForm(n) {
        if (typeof n === "number") {
          this.searchData.page = this.searchData.page + n;
        }

        /*this.searchData.beginTime = this.searchData.rangeDate[0]
        this.searchData.endTime = this.searchData.rangeDate[1]*/

        searchOrder(this.searchData).then(response => {
          if (response.code === 200) {
            this.dataList = response.page.list;
            this.searchData.page = response.page.currPage;
            this.searchData.totalPage = response.page.totalPage;
            this.searchData.totalCount = response.page.totalCount;
          }
        });
      },
      resetForm() {
        this.$refs['searchForm'].resetFields()
        this.searchData.name = null
      },
    }
  }

</script>
<style>
  .el-autocomplete {
    width: 100%;
  }

  .el-table .warning-row {
    background: oldlace;
  }

  .el-table .success-row {
    background: #c2f9b3;
  }
</style>
